using System;
using Quiki.ExpressionParsers;

namespace Quiki.ElementFormatters
{
    public class LambdaElementFormatter : ElementFormatterBase
    {
        public LambdaElementFormatter (
            WikiTextElementType elementType, 
            int level,
            Action<WikiTextElement, HtmlFormatterContext> beginAction,
            Action<WikiTextElement, HtmlFormatterContext> endAction)
        {
            this.elementType = elementType;
            this.level = level;
            this.beginAction = beginAction;
            this.endAction = endAction;
        }

        public LambdaElementFormatter (
            WikiTextElementType elementType,
            Action<WikiTextElement, HtmlFormatterContext> beginAction,
            Action<WikiTextElement, HtmlFormatterContext> endAction)
        {
            this.elementType = elementType;
            this.beginAction = beginAction;
            this.endAction = endAction;
        }

        public override bool FormatBegin (WikiTextElement element, HtmlFormatterContext context)
        {
            if (element.ElementType == elementType && element.Level == level)
            {
                if (beginAction != null)
                    beginAction(element, context);
                return true;
            }

            return false;
        }

        public override void FormatEnd (WikiTextElement element, HtmlFormatterContext context)
        {
            if (element.ElementType == elementType && element.Level == level)
            {
                if (endAction != null)
                    endAction (element, context);
                return;
            }
        }

        protected LambdaElementFormatter()
        {
        }

        protected Action<WikiTextElement, HtmlFormatterContext> BeginAction
        {
            get { return beginAction; }
            set { beginAction = value; }
        }

        protected Action<WikiTextElement, HtmlFormatterContext> EndAction
        {
            get { return endAction; }
            set { endAction = value; }
        }

        protected WikiTextElementType ElementType
        {
            get { return elementType; }
            set { elementType = value; }
        }

        private WikiTextElementType elementType;
        private readonly int? level;
        private Action<WikiTextElement, HtmlFormatterContext> beginAction;
        private Action<WikiTextElement, HtmlFormatterContext> endAction;
    }
}